#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>
#include <dlfcn.h>
#include <stdlib.h>

#define TAG "main_test"
#define LOG(...) do { \
	printf("%s %s %d : ", TAG, __FILE__, __LINE__); \
	printf(__VA_ARGS__); } while(0)

typedef void (*watch_func_t)(void *, int, void (*)(),char *,int);

void myCallback(void *ptr,char *info) {
    LOG("ptr=%p\n",ptr);
    LOG("info=%s\n",info);
}

int main() {
    void *handle = dlopen("./libmem_watcher.so", RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "%s\n", dlerror());
        return 1;
    }
	int info_size = 1024;
	char *info = malloc(info_size);

    // 定位符号
    watch_func_t watch = (watch_func_t) dlsym(handle, "watch");
    if (!watch) {
        fprintf(stderr, "%s\n", dlerror());
        dlclose(handle);
        return 1;
    }

    int *i = (int *)malloc(sizeof(int));
	*i = 10;
	LOG("watch ptr = %p value=%d\n",i,*i);
    watch(&i,sizeof(int),myCallback,info,info_size);
    sleep(3);
    LOG("%d,then try to write 20to %p\n",*i,i);
    *i = 20;
	LOG("write successfully ? ptr = %p value=%d\n",i,*i);
    
	int *i2 = (int *)malloc(sizeof(int));
	*i2 = 3;
	LOG("watch ptr = %p value=%d\n",i,*i);
    watch(&i2,sizeof(int),myCallback,info,info_size);
    sleep(3);
    LOG("%d,then try to write 20to %p\n",*i2,i2);
    *i2 = 4;
	LOG("write successfully ? ptr = %p value=%d\n",i2,*i2);
    sleep(3);

    dlclose(handle);
	free(i);
	free(i2);
	free(info);
    return 0;
}

